<template>
  <div id="drawToolbar" class="panel panel-primary drawToolbar" type="draw">
    <div class="panel-heading">
      <h5 class="panel-title text-center" data-i18n="resources.title_DatasourceInfo">标绘菜单</h5>
<!--      <div class="el-icon-close" title="关闭" @click="unBindUIEvent()"></div>-->
      <div><i class="close el-icon-close" @click="unBindUIEvent"></i></div>
    </div>
    <div class="panel-body">
      <div id="panel">
        <div class="btn-group" role="group" aria-label="..." @click="drawTypeChoose">
          <button id="drawPoint" value='Point' type="button" class="btn btn-default">绘点</button>
          <button id="drawLine" value='LineString' type="button" class="btn btn-default">绘线</button>
          <button id="drawPolygon" value='Polygon' type="button" class="btn btn-default">绘面</button>
          <button id="drawCircle" value='Circle' type="button" class="btn btn-default">绘圆</button>
          <button id="outputShp" value='outputShp' type="button" class="btn btn-default">导出</button>
<!--          <button id="none" value='None' type="button" class="btn btn-default">无绘制</button>-->
          <button id="clear" value='Clear' type="button" class="btn btn-default">清除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import globalmf from "@/utils/Global/GlobalMapFunction";

export default {
  name: "DrawPlotting",
  data(){
    return{
      draw:null,
      drawFeatures:[],
    }
  },
  props: {
    plotConfig: {
      type: Object,
      default() {
        return {
          map:null,
          overSource:null,
          mcShow:{
            drawPlotting:'allClose',
          },
        }
      }
    },
  },
  mounted() {//mounted函数相当于Init
  },
  methods: {
    unBindUIEvent() {
      let that = this;
      that.plotConfig.mcShow.drawPlotting = "allClose";
    },
    clearInteraction() {
      var that = this;
      globalmf.removeAllDrawInteractions(that.plotConfig.map);
      globalmf.clearSelectedFeature(that.plotConfig.map,that.plotConfig.overSource);//why20220325 这样还算简化吗？
    },
    /*
         * 选择features，导出shp。
         * @param {type} features  ol格式的features
         * @param {type} filename 导出的shp名称
         * @param {type} epsg  epsg的格式为'EPSG:4532' 这样的
         * @returns {undefined}
         */
    exportShp: function (features, filename, epsg) {
      var geojson = new ol.format.GeoJSON();
      //let geomwkts = [];
      for (var i in features) {
        features[i].getGeometry().applyTransform(ol.proj.getTransform("EPSG:4490", epsg));
        //geomwkts.push(new ol.format.WKT().writeFeature(features[i]))
      }
      var geojsonstr = geojson.writeFeaturesObject(features);
      for (var i = 0; i < geojsonstr.features.length; i++)
      {
        var feaCoors = geojsonstr.features[i].geometry.coordinates;
        if (geojsonstr.features[i].geometry.type == "MultiPolygon") {//多部件的是MultiPolygon，。带洞的一个面是正常的Polygon
          geojsonstr.features[i].geometry.type = "Polygon";
          var gjsj = [];
          for (var j = 0; j < feaCoors.length; j++) {
            gjsj.push(feaCoors[j][0]);
          }
          geojsonstr.features[i].geometry.coordinates = [];
          geojsonstr.features[i].geometry.coordinates.push(gjsj);
        } else if (feaCoors.length > 1) {
          geojsonstr.features[i].geometry.coordinates = [];
          geojsonstr.features[i].geometry.coordinates.push(feaCoors);
        }
        var props = geojsonstr.features[i].properties;
        for (var j in props) {
          var value = props[j];
          geojsonstr.features[i].properties[j] = unescape(value.replace(/\\u/gi, '%u'));
        }
      }
      let fd = new FormData();
      //fd.append("geoms", geomwkts.join("&&"));
      fd.append("geoms",JSON.stringify(geojsonstr));
      fd.append("epsg", epsg);
      let outputUrl = gConfig.spbtdir.defaulturl + gConfig.spbturl.portal.upload.writeShpfile;
      axios({
        method: "POST",
        url: outputUrl,
        data: fd,
        responseType: "blob"
      }).then(response => {
        //why20220323获取当前时间
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
          month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
        }
        let currentDate = date.getFullYear() + "" + month + "" + strDate
            + "_" + date.getHours() + "" + date.getMinutes() + "" + date.getSeconds();

        let blob = new Blob([response.data], {type: "application/zip"});
        let url = window.URL.createObjectURL(blob);
        const link = document.createElement("a"); // 创建a标签
        link.href = url;
        link.download = currentDate; // 重命名文件
        link.click();
        URL.revokeObjectURL(url); // 释放内存
      }).catch(
          error => this.$message.error(error)
      );
    },
    drawTypeChoose(e){
      let that=this;
      let type=e.target.attributes.getNamedItem("value").nodeValue;
      switch (type){
        case "None":
          that.clearInteraction();
          break;
        case "Clear":
          that.clearInteraction();
          that.plotConfig.overSource.clear();
          break;
        case "outputShp"://导出shp文件
          that.drawFeatures = [];
          that.plotConfig.overSource.forEachFeature(function (feature) {
            //if (loadshp&&feature.get("featureid") == loadshp.featureid) {
            that.drawFeatures.push(feature);
            //}
          });
          that.exportShp(that.drawFeatures, '导出shp', "EPSG:4490");
          break;
        case "Point":
        case "LineString":
        case "Polygon":
        case "Circle":
          that.clearInteraction();
          that.draw = new ol.interaction.Draw({
            source: that.plotConfig.overSource,
            type: type,
            snapTolerance: 20,
            style: that.style,
          });
          that.plotConfig.map.addInteraction(that.draw);
          break;

      }
    },
  },
}
</script>

<style scoped>
.drawToolbar {
  position: absolute;
  /*top: 50px;*/
  right: 10px;
  width: 380px;
  text-align: center;
   z-index: 100;
  border-radius: 4px;
  font-size: 20px;
  font-weight: normal;
  margin: 0px 5px;
  margin-bottom: 20px;
  background-color: #fff;
  border: 1px solid transparent;
  border-radius: 0 4px 4px 0;

}
.drawToolbar .panel-heading {
  padding: 5px 5px;
  border-bottom: 1px solid transparent;
  border-top-right-radius: 3px;
  border-top-left-radius: 3px;
  color: #fff;
  background-color: #008680;
  border-color: #ccc;
}
.drawToolbar .panel-heading .panel-title{
  margin-top: 0;
  margin-bottom: 0;
  font-size: 16px;
}
.drawToolbar .panel-body {
  padding: 15px;
}
.drawToolbar .panel-body button{
  background-color: #008680;
  border-color: #ccc;
  position: relative;
  float: left;
  font-size: 14px;
  font-weight: normal;
  line-height: 1.428571429;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  cursor: pointer;
  border: 1px solid transparent;
  border-radius: 4px;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -o-user-select: none;
  user-select: none;
  padding: 3px 9px;
  margin: 0px 5px;
  color: #fff;
  border-radius: 4px;
  cursor: pointer;
  display: inline-block;
}
.drawToolbar .btn-group{
  position: relative;
  display: inline-block;
  vertical-align: middle;
}
  .close{
    top: 8px;
    position: absolute;
    right: 5px;
  }
</style>
